import { defineStore } from 'pinia'
import type { RouteRecordRaw } from 'vue-router'

import { getUserInfo, loginFun, logout, register, userUpDate, getScanCode, scanLogin, pcAuthBind } from '@/api/user'
import { TOKEN_KEY } from '@/enums/cacheEnums'
import { PageEnum } from '@/enums/pageEnum'
import router, { filterAsyncRoutes } from '@/router'
import { clearAuthInfo, getToken } from '@/utils/auth'
import cache from '@/utils/cache'
import { toRaw } from 'vue'
import { get } from '@vueuse/core'
export interface UserState {
    token: string
    userInfo: Record<string, any>
    routes: RouteRecordRaw[]
    perms: string[]
}

const useUserStore = defineStore({
    id: 'user',
    state: (): UserState => ({
        token: getToken() || '',
        // 用户信息
        userInfo: {},
        // 路由
        routes: [],
        // 权限
        perms: []
    }),
    getters: {},
    actions: {
        resetState() {
            this.token = ''
            this.userInfo = {}
            this.perms = []
        },
        login(playload: any) {
            const { account, password } = playload
            return new Promise((resolve, reject) => {
                loginFun({
                    account: account.trim(),
                    password: password
                })
                    .then(async (data) => {
                        this.token = data.token
                        cache.set(TOKEN_KEY, data.token)
                        await this.getUserInfoFun()
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        logout() {
            return new Promise((resolve, reject) => {
                logout()
                    .then(async (data) => {
                        console.log('退出登录了')
                        this.token = ''
                        await router.push(PageEnum.LOGIN)
                        clearAuthInfo()
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        getUserInfoFun() {
            return new Promise((resolve, reject) => {
                getUserInfo()
                    .then((data) => {
                        this.userInfo = data
                        this.perms = data.permissions
                        // this.routes = filterAsyncRoutes(data.menu)
                        this.routes = router.getRoutes()
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        // 注册
        register(playload: any) {
            return new Promise((resolve, reject) => {
                register(playload).then(async (data) => {
                    await this.login({
                        account: playload.account,
                        password: playload.password
                    })
                    resolve(data)
                }).catch((error) => {
                    reject(error)
                })
            })
        },
        // 修改
        userUpData(playload: any) {
            return new Promise((resolve, reject) => {
                userUpDate(playload).then(async (data) => {
                    await this.getUserInfoFun()
                    resolve(data)
                }).catch((error) => {
                    reject(error)
                })
            })
        },
        // 获取登录二维码
        getLoginQrCode(url: string) {
            return new Promise((resolve, reject) => {
                getScanCode({url: url})
                    .then((data) => {
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },
        // 二维码登录
        handlerLogin(code: string, state: string) {
            return new Promise((resolve, reject) => {
                scanLogin({code, state})
                    .then(async (data) => {
                        this.token = data.token
                        cache.set(TOKEN_KEY, data.token)
                        await this.getUserInfoFun()
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        },

        // 绑定微信
        bindCodeLogin(code: string) {
            return new Promise((resolve, reject) => {
                pcAuthBind({code})
                    .then(async (data) => {
                        // this.token = data.token
                        // cache.set(TOKEN_KEY, data.token)
                        // await this.getUserInfoFun()
                        resolve(data)
                    })
                    .catch((error) => {
                        reject(error)
                    })
            })
        }
    }
})

export default useUserStore
